package com.saascloud.web.config;

import com.saascloud.thread.ThreadTaskUtils;
import com.saascloud.web.core.filter.CorsFilter;
import com.saascloud.web.core.filter.SaasContextUtilFilter;
import com.saascloud.web.core.handler.GlobalExceptionHandler;
import com.saascloud.web.core.handler.GlobalResponseBodyHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.Executor;

/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/5/23 10:42
 * @Version: 1.0
 * @Description:
 */
@Slf4j
public class WebAutoConfiguration {

    private static final int MAX_SIZE = 16;
    private static final int KEEP_ALIVE_SECOND = 600;
    private static final int CORE_SIZE = 8;

    @Bean
    @ConditionalOnProperty(name = "exception.handler.enabled", havingValue = "true", matchIfMissing = true)
    @ConditionalOnMissingBean(GlobalExceptionHandler.class)
    public GlobalExceptionHandler globalExceptionHandler() {
        return new GlobalExceptionHandler();
    }


    @Bean
    @ConditionalOnProperty(name = "saas.resp.body.wrapper", havingValue = "true", matchIfMissing = true)
    @ConditionalOnMissingBean(GlobalResponseBodyHandler.class)
    public GlobalResponseBodyHandler facadeserverResponseBodyHandler() {
        return new GlobalResponseBodyHandler();
    }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterFilterRegistrationBean() {
        CorsFilter corsFilter = new CorsFilter();
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(corsFilter);
        bean.setOrder(Integer.MIN_VALUE);
        bean.setName("corsFilter");
        return bean;
    }


    @Bean
    public SaasContextUtilFilter tenantFilter() {
        return new SaasContextUtilFilter();
    }

    @Bean
    public FilterRegistrationBean<SaasContextUtilFilter> tenantFilterFilterRegistrationBean(SaasContextUtilFilter saasContextUtilFilter) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(saasContextUtilFilter);
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setName("tenantFilter");
        return filterRegistrationBean;
    }

    /**
     * 替换默认线程池
     *
     * @return
     */
    @Bean()
    @Primary
    public Executor getAsyncExecutor() {
        return ThreadTaskUtils.newDynamicThreadPool(CORE_SIZE, MAX_SIZE, KEEP_ALIVE_SECOND);
    }

}
